package controllers

import (
	"myapp/dal/model"
	"myapp/dal/query"
	"myapp/middleware"
	"myapp/validates"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type CreateUserInput struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	RoleID   int64  `json:"role_id" binding:"required"`
}

func CreateUser(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var input CreateUserInput
		if err := c.ShouldBindJSON(&input); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "密码加密失败"})
			return
		}

		user := model.User{
			Username: input.Username,
			Password: string(hashedPassword),
			RoleID:   input.RoleID,
		}

		if err := db.Create(&user).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "创建用户失败"})
			return
		}

		c.JSON(http.StatusOK, gin.H{"message": "用户创建成功"})
	}
}

func ProfileHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		var dto validates.UserProfile
		if err := c.ShouldBindJSON(&dto); err != nil {
			errs, ok := err.(validator.ValidationErrors)
			if !ok {
				// 非validator.ValidationErrors类型错误直接返回
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  err.Error(),
				})
				return
			}
			// validator.ValidationErrors类型错误则进行翻译
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  middleware.GetFirstErrorMessage(errs),
			})
			return
		}

		userId, _ := c.Get("userID")
		if v, ok := userId.(uint); ok {
			nd := model.User{
				Name:      dto.Name,
				Company:   dto.Company,
				Position:  dto.Position,
				Phone:     dto.Phone,
				AvatarURL: dto.AvatarUrl,
				BlImage:   dto.BlImage,
			}

			query.User.Where(query.User.ID.Eq(int32(v))).Updates(&nd)

			c.JSON(http.StatusOK, gin.H{"code": 0, "data": nd.ID})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  "程序异常",
		})

	}
}

func UserInfoHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		userId, _ := c.Get("userID")
		if v, ok := userId.(uint); ok {

			query.User.CreatedAt.DateFormat("%W %M %Y")
			user, _ := query.User.Where(query.User.ID.Eq(int32(v))).Take()

			c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
				"user": user,
			}})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  "程序异常",
		})
	}
}
